package cn.meye11.crm.common.mybatis.handler;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Slf4j
public class SetStringTypeHandler extends BaseTypeHandler<Set<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Set<String> parameters, JdbcType jdbcType) throws SQLException {

        if (parameters != null && !parameters.isEmpty()) {

            ps.setString(i, StringUtils.join(parameters.toArray(new String[]{}), ","));
        }
    }

    @Override
    public Set<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {

        return toSet(rs.getString(columnName));
    }

    @Override
    public Set<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {

        return toSet(rs.getString(columnIndex));
    }

    @Override
    public Set<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {

        return toSet(cs.getString(columnIndex));
    }

    private Set<String> toSet(String str) {

        if (StringUtils.isBlank(str)) return Collections.emptySet();

        String[] ret = StringUtils.split(str, ",");

        if (ret == null || ret.length < 1) return Collections.emptySet();

        return new HashSet<>(Arrays.asList(ret));
    }
}
